package practice.sort.compare;

import practice.sort.Sort;

/**
 * @Description:
 * @Author Ammar
 * @Create 2023/8/9 20:30
 */
public class InsertionSort extends Sort {
    @Override
    public void sort() {
        for (int i = 1; i < nums.length; i++) {
            insert(searchIndex(i), i);
        }
    }

    public void insert(int index, int numIndex) {
        int val = nums[numIndex];
        for (int i = numIndex; i > index; i--) {
            nums[i] = nums[i - 1];
        }
        nums[index] = val;
    }

    public int searchIndex(int index) {
        int left = 0;
        int right = index;
        while (left < right) {
            int mid = left + ((right - left) >> 1);
            if (nums[index] >= nums[mid]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
}
